<template>
  <div class="container">
    <div class="settings-panel">
      <div class="form-row">
        <div class="form-group">
          <label>背景颜色1</label>
          <div class="input-group">
            <input
              type="color"
              v-model="settings.color1"
              class="color-picker"
            />
            <button @click="randomizeBg" class="icon-btn" title="随机背景">
              🎲
            </button>
          </div>
        </div>

        <div class="form-group">
          <label>背景颜色2</label>
          <div class="input-group">
            <input
              type="color"
              v-model="settings.color2"
              class="color-picker"
            />
          </div>
        </div>
      </div>

      <div class="form-row">
        <div class="form-group">
          <label>字体大小（px）</label>
          <div class="input-group">
            <input
              type="number"
              v-model="settings.fontSize"
              min="24"
              max="120"
              step="2"
              class="font-size-input"
              @input="handleFontSizeInput"
            />
          </div>
        </div>

        <div class="form-group">
          <label>字体颜色</label>
          <div class="input-group">
            <input type="color" v-model="settings.textColor" />
          </div>
        </div>
      </div>
    </div>

    <textarea
      v-model="text"
      placeholder="输入文章标题..."
      style="width: 100%; height: 100px"
    ></textarea>
    <button @click="generateCover" class="primary-btn">生成封面</button>

    <div class="preview-container" style="width: 100%">
      <canvas ref="canvasRef" style="width: 100%" height="300"></canvas>
    </div>

    <button
      @click="downloadImage"
      :disabled="!canDownload"
      class="secondary-btn"
    >
      <span class="icon">⬇️</span> 下载图片
    </button>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';

// 响应式状态
const canvasRef = ref(null);
const ctx = ref(null);
const text = ref('');
const canDownload = ref(false);

const settings = reactive({
  fontSize: '24',
  textColor: '#ffffff',
  color1: '#0984e3',
  color2: '#6c5ce7',
});

// 工具函数
const getRandomColor = () => {
  return `#${Math.floor(Math.random() * 16777215)
    .toString(16)
    .padStart(6, '0')}`;
};

const debounce = (fn, delay) => {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.apply(this, args), delay);
  };
};

// Canvas 相关方法
const initCanvas = () => {
  ctx.value.fillStyle = '#2d3436';
  ctx.value.fillRect(0, 0, canvasRef.value.width, canvasRef.value.height);
};

const createGradient = () => {
  try {
    const gradient = ctx.value.createLinearGradient(
      0,
      0,
      canvasRef.value.width,
      canvasRef.value.height
    );
    gradient.addColorStop(0, settings.color1);
    gradient.addColorStop(1, settings.color2);
    return gradient;
  } catch (error) {
    console.error('渐变创建失败:', error);
    return '#2d3436';
  }
};

// const wrapText = (text, x, y, maxWidth, lineHeight, maxLines = 3) => {
//   const paragraphs = text.split('\n');
//   // const paragraphs = text;

//   const allLines = [];

//   paragraphs.forEach((paragraph) => {
//     let currentLine = '';
//     const words = paragraph.split(/(\s+)/g).filter((w) => w !== '');

//     words.forEach((word) => {
//       const testLine = currentLine + word;
//       const metrics = ctx.value.measureText(testLine);

//       if (metrics.width > maxWidth && currentLine !== '') {
//         allLines.push(currentLine.trim());
//         currentLine = word;
//       } else {
//         currentLine = testLine;
//       }
//     });

//     if (currentLine.trim() !== '') {
//       allLines.push(currentLine.trim());
//     }
//   });

//   const displayLines = allLines.slice(0, maxLines);
//   const totalHeight = displayLines.length * lineHeight;
//   const startY = y - totalHeight / 2 + lineHeight / 2;

//   displayLines.forEach((line, index) => {
//     const lineY = startY + index * lineHeight;
//     ctx.value.fillText(line, x, lineY);
//   });

//   if (allLines.length > maxLines) {
//     ctx.value.fillText('...', x, startY + maxLines * lineHeight);
//   }
// };

const wrapText = (text, x, y, maxWidth, lineHeight, maxLines = 3) => {
  const textStr = String(text || '');
  const words = textStr.split('');
  let currentLine = '';
  const lines = [];

  // 遍历每个字符
  for (let i = 0; i < words.length; i++) {
    const char = words[i];
    const testLine = currentLine + char;
    const metrics = ctx.value.measureText(testLine);

    // 如果当前行加上新字符会超出最大宽度，则换行
    if (metrics.width > maxWidth && currentLine !== '') {
      lines.push(currentLine);
      currentLine = char;
    } else {
      currentLine = testLine;
    }
  }

  // 添加最后一行
  if (currentLine) {
    lines.push(currentLine);
  }

  // 限制显示的行数
  const displayLines = lines.slice(0, maxLines);
  const totalHeight = displayLines.length * lineHeight;
  const startY = y - totalHeight / 2 + lineHeight / 2;

  // 绘制每一行文字
  displayLines.forEach((line, index) => {
    const lineY = startY + index * lineHeight;
    ctx.value.fillText(line, x, lineY);
  });

  // 如果有更多行但被截断了，显示省略号
  if (lines.length > maxLines) {
    ctx.value.fillText('...', x, startY + maxLines * lineHeight);
  }
};

// 主要功能方法
const generateCover = (inputText = text.value) => {
  if (inputText instanceof Event) {
    inputText = text.value;
  }
  if (!inputText && inputText !== 0) return;

  ctx.value.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height);

  // 绘制背景
  ctx.value.fillStyle = createGradient();
  ctx.value.fillRect(0, 0, canvasRef.value.width, canvasRef.value.height);

  // 文字样式配置
  ctx.value.fillStyle = settings.textColor;
  ctx.value.font = `bold ${settings.fontSize}px "Segoe UI", sans-serif`;
  ctx.value.textAlign = 'center';

  // 主标题文字
  wrapText(
    String(inputText),
    canvasRef.value.width / 2,
    canvasRef.value.height / 2,
    canvasRef.value.width - 80,
    parseInt(settings.fontSize) * 1.5
  );

  // 水印文字
  ctx.value.fillStyle = 'rgba(255,255,255,0.15)';
  ctx.value.font = '18px "Courier New", monospace';
  ctx.value.fillText(
    'techcover.autogen-xby',
    canvasRef.value.width - 120,
    canvasRef.value.height - 25
  );

  canDownload.value = true;
};

const randomizeBg = () => {
  settings.color1 = getRandomColor();
  settings.color2 = getRandomColor();
  generateCover();
};

const downloadImage = () => {
  const link = document.createElement('a');
  link.download = `cover-${Date.now()}.png`;
  link.href = canvasRef.value.toDataURL();
  link.click();
};

const handleFontSizeInput = debounce((e) => {
  const size = Math.min(120, Math.max(24, settings.fontSize || 56));
  settings.fontSize = size.toString();
  generateCover();
}, 500);

// 加载设置
const loadSettings = async () => {
  try {
    // 检查是否在 Chrome 扩展环境中
    if (
      typeof chrome !== 'undefined' &&
      chrome.storage &&
      chrome.storage.sync
    ) {
      const storedSettings = await chrome.storage.sync.get(
        Object.keys(settings)
      );
      Object.assign(settings, {
        ...settings,
        ...storedSettings,
        fontSize: Math.min(120, Math.max(24, storedSettings.fontSize || 56)),
      });
    }
    generateCover('文字生成');
  } catch (error) {
    console.error('加载设置失败:', error);
  }
};

// 监听设置变化
watch(
  settings,
  (newSettings, oldSettings) => {
    const changedKey = Object.keys(newSettings).find(
      (key) => newSettings[key] !== oldSettings[key]
    );
    if (
      changedKey &&
      typeof chrome !== 'undefined' &&
      chrome.storage &&
      chrome.storage.sync
    ) {
      chrome.storage.sync.set({ [changedKey]: newSettings[changedKey] });
      generateCover();
    }
  },
  { deep: true }
);

// 初始化
onMounted(() => {
  ctx.value = canvasRef.value.getContext('2d');
  initCanvas();
  loadSettings();
});
</script>

<style scoped>
@import './popup.css';
</style>
